import logging
import os
from sqlalchemy import Result, select, text
from sqlalchemy.ext.asyncio import AsyncSession

from price_analysis.utils.file_support import (
    read_ocr_file,
    write_ocr_file,
    JsonFileSupport,
)
from price_analysis.core.config import settings

logger = logging.getLogger("main")


async def get_materials_by_param(
    session: AsyncSession,
    param: str,
) -> list[str] | None:
    stmt = text("SELECT name FROM FSSC WHERE name LIKE '%' || :param || '%'")
    result: Result = await session.execute(stmt, {"param": param})

    if result:
        return [item[0] for item in result.all()]

    return None


async def get_materials(session: AsyncSession) -> list[str]:
    logger.info("Запрос в справочник ФССЦ всех данных")
    stmt = text("SELECT Name FROM FSSC WHERE level == 4")
    result: Result = await session.execute(stmt)

    return [str(item[0]) for item in result]


async def get_material_index_in_FSSC(session: AsyncSession, name: str) -> str:
    logger.info("Запрос в справочник ФССЦ кода товара")
    stmt = text("""SELECT Code FROM FSSC WHERE Name = :param""")

    result: Result = await session.execute(stmt, {"param": name})
    index = result.fetchone()[0]
    logger.info(f"кода товара в ФССЦ {index}")
    return index


async def get_all_in_fssc(filename: str) -> list[dict]:
    logger.info(f"Файл {filename} прочитан")
    return await read_ocr_file(filename)


async def delete_item_in_fssc(idx: int):
    full_path_in_fssc = os.path.join(settings.ocr_data_path, "in_fssc" + ".json")
    full_path_to_request_prices = os.path.join(
        settings.ocr_data_path, "to_request_prices" + ".json"
    )

    in_fssc: list[dict] = await get_all_in_fssc(filename=full_path_in_fssc)
    to_request_prices: list[dict] = await get_all_in_fssc(
        filename=full_path_to_request_prices
    )

    in_fssc_new = [item for item in in_fssc if item["id"] != idx]

    item_to_move = next((item for item in in_fssc if item["id"] == idx), None)

    if item_to_move:
        del item_to_move["id"]
        del item_to_move["name_in_fssc"]
        del item_to_move["idex_in_fssc"]
        to_request_prices.append(item_to_move)

    await write_ocr_file(full_path_in_fssc, in_fssc_new)
    await write_ocr_file(full_path_to_request_prices, to_request_prices)

    return in_fssc_new


async def get_search_online_result() -> list[dict]:
    report_full_path = os.path.join(settings.main_report_path, "main_report" + ".json")
    report_data = JsonFileSupport(report_full_path)
    return await report_data.read_json_file()


async def get_data_for_search_online() -> list[dict]:
    to_request_prices_full_path = os.path.join(
        settings.ocr_data_path, "to_request_prices" + ".json"
    )
    to_request_prices_data = JsonFileSupport(to_request_prices_full_path)
    return await to_request_prices_data.read_json_file()


def get_path_list(data: list[dict]) -> list[str]:
    path_list = []
    for item in data:
        path_list.append(item["img_path"])
    return path_list


async def delete_offer(idx: int) -> list[dict]:
    full_path_to_report = f"{settings.main_report_path}/main_report.json"
    full_path_to_request_offer = f"{settings.ocr_data_path}/to_request_offer.json"

    main_report = JsonFileSupport(full_path_to_report)
    request_offer = JsonFileSupport(full_path_to_request_offer)

    main_report_data = await main_report.read_json_file()
    main_report_new = [item for item in main_report_data if item["id"] != idx]
    await main_report.write_json_file(main_report_new)

    item_to_delete = next(
        (item for item in main_report_data if item["id"] == idx), None
    )
    if item_to_delete:
        del item_to_delete["prices_data"]
        await request_offer.add_to_json_file(item_to_delete)

    return main_report_new
